import { rmFieldsFromObject } from "../../utils/index.js";

let io;
const syncClients = async () => {
  const clients = await io.fetchSockets();
  const data = clients.map((item) => ({
    id: item.id,
    room: Array.from(item.rooms)[1],
  }));
  io.in("admin").emit("clientsChange", data);
};

/**
 * 提示版本升级
 * 如果用户的app版本，低于数据库登记的最新版本，那就弹窗提示
 * 弹窗分为强制和非强制，强制没有关闭按钮
 */
export default (ioTemp, server) => {
  io = ioTemp;
  // main namespace
  io.on("connection", async (socket) => {

    const urlParams = rmFieldsFromObject(socket.handshake.query, ["EIO", "transport", "t"]);
    const isAdmin = Object.keys(urlParams).length === 0;
    if (isAdmin) {
      socket.join("admin");
    } else {
      socket.join("user");
    }
    // else{
    //     socket.join(JSON.stringify(urlParams));
    //     const sockets = await io.in("room1").fetchSockets();
    //     io.to("admin").emit();
    // }
    // const res = await io.in("admin").fetchSockets();
    // const info = getUsefulInfo(res[0]);
    // console.log(res[0].handshake.query);
    syncClients(io);

    socket.on("disconnect", () => {
      syncClients();
    });
  });
  io.listen(server); 
};
